package org.example.new_hbps_backend_reconstruction.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.new_hbps_backend_reconstruction.common.constants.AuthConstants;
import org.example.new_hbps_backend_reconstruction.dto.PatientSessionDTO;
import org.example.new_hbps_backend_reconstruction.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 丁利军
 * @date 2025年10月10日 13:22
 * @description token刷新拦截器
 */

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 👉 放行 OPTIONS 请求（预检请求）
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            //response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String tokenHeader = request.getHeader("Authorization");
        if (StrUtil.isBlank(tokenHeader) || !tokenHeader.startsWith("Bearer ")) {
            // 无效请求，直接放行（或按需拦截）
            return true;
        }
// 移除 "Bearer " 前缀，保留 token
        String token = tokenHeader.substring(7);
//        // 1.获取请求头中的token
//        String token = request.getHeader("Authorization");
//        if (StrUtil.isBlank(token)) {
//            return true;
//        }

        // 2.基于TOKEN获取redis中的用户
        String key  = AuthConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }

        // 5.将查询到的hash数据转为UserDTO
        PatientSessionDTO userDTO = new PatientSessionDTO();
        userDTO.setPatientUid(Long.valueOf((String) userMap.getOrDefault("patientUid","0")));
        userDTO.setUsername((String) userMap.getOrDefault("username",""));
        userDTO.setPhoneNumber((String) userMap.getOrDefault("phoneNumber",""));
        userDTO.setWxUid((String) userMap.getOrDefault("wxUid",""));
        userDTO.setToken(token);

        UserHolder.saveUser(userDTO);
        // 7.刷新token有效期
        stringRedisTemplate.expire(key, AuthConstants.LOGIN_USER_TTL_MINUTES, TimeUnit.MINUTES);

        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
